<template>
  <el-form :model="activity" label-width="100px" style="max-width: 600px">
    <el-form-item label="标题">
      <el-input v-model="activity.title" placeholder="请输入活动标题" />
    </el-form-item>
    <el-form-item label="地点">
      <el-input v-model="activity.location" placeholder="请输入活动地点" />
    </el-form-item>
    <el-form-item label="开始时间">
      <el-date-picker v-model="activity.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%" />
    </el-form-item>
    <el-form-item label="结束时间">
      <el-date-picker v-model="activity.endTime" type="datetime" placeholder="选择结束时间" style="width: 100%" />
    </el-form-item>
    <el-form-item label="内容">
      <el-input v-model="activity.content" type="textarea" placeholder="请输入活动内容" />
    </el-form-item>
    <el-form-item label="分数">
      <el-input-number v-model="activity.point" :min="0" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="createActivity">保存为草稿</el-button>
      <el-button type="success" @click="submitActivity">直接提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const activity = reactive({
  actId: null,
  title: '',
  content: '',
  startTime: '',
  endTime: '',
  location: '',
  status: 'DRAFT',
  orgId: Number(localStorage.getItem('loginId')),
  point: 0
})

const createActivity = async () => {
  try {
    const response = await axios.post(
      `http://localhost:8080/orgs/${activity.orgId}/activities`,
      { ...activity, status: 'DRAFT' }
    );
    if (response.data && response.data.code === 200) {
      ElMessage.success('活动已保存为草稿');
      // 可跳转到活动列表或详情页
    } else {
      ElMessage.error(response.data && response.data.msg ? response.data.msg : '创建失败');
    }
  } catch (error) {
    ElMessage.error('创建失败');
  }
};

const submitActivity = async () => {
  try {
    // 第一步：先创建活动，状态为PENDING
    const createRes = await axios.post(
      `http://localhost:8080/orgs/${activity.orgId}/activities`,
      { ...activity, status: 'PENDING' }
    );
    if (createRes.data && createRes.data.code === 200) {
      const activityId = createRes.data.actId;
      // 第二步：提交活动申请，orgId为路径参数
      const submitRes = await axios.post(
        `http://localhost:8080/orgs/activities/submit/${activity.orgId}`,
        { "activityId": activityId }
      );
      if (submitRes.data && submitRes.data.code === 200) {
        ElMessage.success('活动已直接提交');
        // 可跳转到活动列表或详情页
      } else {
        ElMessage.error(submitRes.data && submitRes.data.msg ? submitRes.data.msg : '提交失败');
      }
    } else {
      ElMessage.error(createRes.data && createRes.data.msg ? createRes.data.msg : '创建失败');
    }
  } catch (error) {
    ElMessage.error('提交失败');
  }
};
</script>